'use client'
import React, { use, useEffect, useState } from 'react'
import PageTitle from '@/components/admin/common/PageTitle';
import { useRouter } from 'next/navigation';
import request from '@/utils/request';
import message from '@/components/common/message';
import { isEqual } from 'lodash';
import Loading from '@/components/common/Loading';
import SuperInput from '@/components/admin/common/SuperInput';
import SuperNumberInput from '@/components/admin/common/SuperNumberInput';
import SuperCheckbox from '@/components/admin/common/SuperCheckbox';
import SuperSelect from '@/components/admin/common/SuperSelect';
import ImageUpload from '@/components/admin/common/ImageUpload';
import SuperImageGallery from '@/components/admin/common/SuperImageGallery';
import SuperCollectionSelect from '@/components/admin/products/SuperCollectionSelect';
import SuperSkusSelect from '@/components/admin/products/SuperSkusSelect';

export default function Products({ params }) {
  const { id } = use(params);
  const [loaded, setLoaded] = useState(false);
  const [originData, setOriginData] = useState(null);
  const [data, setData] = useState(null);
  const [collections, setCollections] = useState([]);
  const router = useRouter();
  const [changed, setChanged] = useState(false);

  const saveDataValues = () => {
    if (!changed) {
      router.back();
    } else {
      request(`/api/admin/products`, { method: 'PUT', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } })
        .then((res) => {
          if (res.code === 0) {
            message.success('保存成功');
            fetchData(id);
          } else {
            message.error(res.codeMap(res.code));
          }
        })
    }
  }

  const fetchData = async (id) => {
    request(`/api/admin/products/${id}`)
      .then((res) => {
        if (res.code === 0) {
          setOriginData(res.data);
          setData(res.data);
          setLoaded(true);
        } else {
          message.error(res.codeMap[res.code]);
        }
      });
    fetch('/api/admin/collections?limit=99999999&page=1', { method: 'GET' })
      .then((res) => res.json())
      .then((res) => {
        if (res.code !== 0) { return message.error(res.codeMap[res.code]); }
        setCollections(res.data);
      })
  }

  useEffect(() => {
    fetchData(id);
  }, [id]);

  const resetData = () => { setData(originData); }

  const changeHandle = (key, value, type) => { setData(prev => { return { ...prev, [type]: { ...prev[type], [key]: value } } }); }

  const handleChangeImages = (value) => {
    request(`/api/admin/products`, { method: 'PATCH', body: JSON.stringify({ product_id: data.product.id, data: value, type: 'images' }), headers: { 'Content-Type': 'application/json' } })
      .then((res) => {
        if (res.code === 0) {
          setData(prev => { return { ...prev, images: value } });
          setOriginData(prev => { return { ...prev, images: value } });
          message.success('图片更新成功');
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }

  const handleChangeCollections = (value) => {
    setData(prev => { return { ...prev, collections: value } });
    setOriginData(prev => { return { ...prev, collections: value } });
    request(`/api/admin/products`, { method: 'PATCH', body: JSON.stringify({ product_id: data.product.id, data: value, type: 'collections' }), headers: { 'Content-Type': 'application/json' } })
      .then((res) => {
        if (res.code === 0) {
          message.success('分类更新成功');
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }

  const handleChangeSkus = (value) => {
    
  }

  useEffect(() => {
    const isChange = !isEqual(originData, data);
    setChanged(isChange);
  }, [data, originData]);

  const content = (
    <div>
      <PageTitle title={`${data?.product?.title} - 编辑`} extraButtonText={changed ? '重置' : ''} onExtraButtonClick={resetData} buttonText={changed ? '保存' : "返回上一页"} onButtonClick={saveDataValues} />
      <div className='mx-auto  rounded-xs shadow-xs my-1 flex gap-4'>
        <div className='content flex-3 flex flex-col gap-4'>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full`} value={data?.product?.title} state={true} handleChange={(value) => changeHandle('title', value, 'product')} placeholder='请输入页面标题' label='标题' />
            <SuperInput className={`w-full`} value={data?.product?.description} state={true} multiline={true} handleChange={(value) => changeHandle('description', value, 'product')} placeholder='请输入页面描述' label='描述' />
            <SuperNumberInput className={`w-full`} value={data?.product?.price} state={true} handleChange={(value) => changeHandle('price', value, 'product')} placeholder='请输入价格' label='价格' />
            <SuperNumberInput className={`w-full`} value={data?.product?.compare_price} state={true} handleChange={(value) => changeHandle('compare_price', value, 'product')} placeholder='请输入原价' label='原价' />
            <SuperNumberInput className={`w-full`} value={data?.product?.stock} state={true} handleChange={(value) => changeHandle('stock', value, 'product')} placeholder='请输入库存' label='库存' />
            <SuperImageGallery value={data?.images} product_id={data?.product?.id} state={true} handleChange={(value) => handleChangeImages(value)} placeholder='上传产品图片' label='产品图片' />
            <SuperCollectionSelect options={collections} values={data?.collections} state={true} onChange={(value) => handleChangeCollections(value)} label='添加产品分类' />
            {/* <SuperSkusSelect state={true} label={`更新sku`} handleChange={(value) => handleChangeSkus(value)} value={data?.skus} className={``}/> */}
          </div>
          <div className='bg-white p-4 rounded-sm'>
            <SuperInput className={`w-full`} value={data?.product?.slug} state={true} handleChange={(value) => changeHandle('slug', value, 'product')} placeholder='请输入页面别名' label='别名（用于搜索引擎优化，不填写会自动生成）' />
            <SuperInput className={`w-full`} value={data?.product?.meta_title} state={true} handleChange={(value) => changeHandle('meta_title', value, 'product')} placeholder='请输入Meta标题' label='Meta标题（用于搜索引擎优化）' />
            <SuperInput className={`w-full`} value={data?.product?.meta_description} state={true} handleChange={(value) => changeHandle('meta_description', value, 'product')} placeholder='请输入Meta描述' label='Meta描述（用于搜索引擎优化）' />
            <SuperInput className={`w-full`} value={data?.product?.slug && `${window && window.location.origin}/products/${data?.product.slug}`} state={false} handleChange={(value) => changeHandle('url', value, 'product')} label='访问链接' />
          </div>
        </div>
        <div className='silder flex-1 bg-white p-4 rounded-sm h-fit sticky top-[64px]'>
          <SuperCheckbox className='w-full!' value={data?.product?.status} state={true} checked={data?.product?.status === 0 ? true : false} onChange={(value) => changeHandle('status', value ? 0 : 1, 'product')} label='状态' />
          <div> <SuperSelect className='w-full!' value={data?.product?.template} state={true} onChange={(value) => changeHandle('template', value, 'product')} label={'模板'} placeholder='选择模板' options={data?.product?.templates || []} /> </div>
          <ImageUpload value={data?.product?.cover} state={true} handleChange={(value) => changeHandle('cover', value, 'product')} placeholder='上传封面图片' label='封面图片' />
          <SuperInput className='w-full!' value={data?.product?.created_at && new Date(data?.product?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('created_at', value, 'product')} placeholder='创建时间' label='创建时间' />
          <SuperInput className='w-full!' value={data?.product?.updated_at && new Date(data?.product?.created_at).toLocaleString()} state={false} handleChange={(value) => changeHandle('updated_at', value, 'product')} placeholder='创建时间' label='创建时间' />
        </div>
      </div>
    </div>
  )

  return (<div> {loaded ? content : <Loading />} </div>)
}
